<?php

class Talktangle_Api_Payment extends Core_Api_Abstract
{
	
    public function getPlugin($currencyCode,$gateway = null,$receiver = null){
        
        if(empty($currency_code) ||  $currency_code == null){
            $currency_code =  Engine_Api::_()->getApi('settings', 'core')->getSetting('idragon.payment.currency', 'USD');
        }
        if(is_null($gateway)){
            $gateway =  Engine_Api::_()->getItem('payment_gateway', 2);
        }
        if(!($gateway->enabled)){
    		return array('error'=>true,'message'=>	Zend_Registry::get('Zend_Translate')->_('Getway is disabled. Please contact to administrator for more details'));
  		}
        
        // payment to admin
        if(empty($receiver) || $receiver == null){
          	$paypalConfig = (array)$gateway->config;
			$paypalConfig['currency'] = $currencyCode;
			$paypalConfig['testMode'] =  $gateway->test_mode;
        	$plugin =  new Talktangle_Plugin_Gateway_PayPal((array)$paypalConfig);  
            return array('error' => false, 'plugin' =>$plugin); 
        }       
    }
    public function paymentPayPal($ads,$title,$returnAction= 'returnbuy',$currency_code =  null,$sender = null,$receiver = null,$returnurl = false){
        
   	    $view = Zend_Registry::get('Zend_View');
        if(empty($sender) || $sender == null){
            $sender = Engine_Api::_()->user()->getViewer();
        }
        
        if(empty($receiver) || $receiver == null){
            $receiver = Engine_Api::_()->user()->getViewer();
        }
        
        
        $orderTable = Engine_Api::_()->getDbtable('orders','payment');
        $order = $orderTable->createRow();
        $order->source_id = $ads->getIdentity();
        $order->source_type = $ads->getType();
        $order->gateway_id = 2;
        $order->user_id = $sender->user_id;
        $order->state = 'pending';
        $order->save();
        
        $plugin = $this->getPlugin('',null, NULL);
        if ( $plugin['error'] == true) {
            return $plugin['message'] ;
        }
        $plugin = $plugin['plugin'];
        
        $schema = 'http://';
        if( !empty($_ENV["HTTPS"]) && 'on' == strtolower($_ENV["HTTPS"]) ) {
            $schema = 'https://';
        }
        $host = $_SERVER['HTTP_HOST'];
        
        $params = array();
        $params['language'] = $receiver->language;
        $localeParts = explode('_', $receiver->language);
        if( count($localeParts) > 1 ) {
            $params['region'] = $localeParts[1];
        }
        
        $params['vendor_order_id'] = md5($order->getIdentity() . rand(0, 100000));
        $params['return_url'] = $schema . $host
                . $view->url(array('action' => $returnAction),'talktangle_payment')
                . '?order_id=' . $order->getIdentity()
                . '&state=' . 'return'
                .'&amount=1'
                .'&vcode='.md5($order->getIdentity().$order->getIdentity());
        $params['cancel_url'] = $schema . $host
                . $view->url(array('action' => $returnAction),'talktangle_payment')
                . '?order_id=' . $order->getIdentity()
                . '&state=' . 'cancel'
                .'&vcode='.md5($order->getIdentity().$order->getIdentity());
   
        $params['price'] = $ads->price;
       
        $params['description'] = 'pay ads';
        $params['amount'] = 1;
      
        $transaction = $this->createTransaction($plugin, $order, $params,$title);
        // Pull transaction params
        $transactionUrl = $plugin->getGateway()->getGatewayUrl();
        $transactionData = $transaction->getData();
        // Handle redirection
        $transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData['token'];
        if($returnurl) return $transactionUrl;
        else return Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector')->gotoUrl($transactionUrl, array('prependBase' => false));
        
        
    }
    
    public function createTransaction($plugin, $order, $params = array(),$title = '') {
    
    	$params['driverSpecificParams']['PayPal'] = array(
                'AMT' => $params['price'],
                'DESC' => $params['description'],
                'CUSTOM' => $order->order_id . rand(1,1000),
                'INVNUM' => $params['vendor_order_id'],
                'ITEMAMT' => $params['price'],
                'ITEMS' => array(
                        array(
                                'NAME' => $title,
                                'DESC' => $params['description'],
                                'AMT' =>  $params['price'],
                                'NUMBER' => $order->order_id,
                                'QTY' => $params['amount'],
                        ),
                )
        );
    	
        $transaction = $plugin->createTransaction($params);
        return $transaction;
    }
    
  
    public function onTransactionReturn($params = array()) {
        // Get order
                
        $orderId = $params['order_id'];
        $vcode = $params['vcode'];
        if(md5($orderId.$orderId)!= $vcode) return;
        $order = Engine_Api::_()->getItem('payment_order',$orderId);
        
        $gateway = Engine_Api::_()->getItem('payment_gateway', 2);
        $plugin = $this->getPlugin('');
        
        if ($plugin['error'] == true){
            throw new Engine_Payment_Plugin_Exception('Gateways error');
            
        }
        $plugin = $plugin['plugin'];
        
        $plugin->getGateway()->getLog()->log('params: '
                    . print_r($params, true), Zend_Log::ERR);
                    
        if( $order->gateway_id != 2 ) {
            throw new Engine_Payment_Plugin_Exception('Gateways do not match');
        }

        if( $params['state'] == 'cancel' ) {
            $order->onCancel();
            return false;
            throw new Payment_Model_Exception('Your payment has been cancelled and ' .
                    'not been charged. If this is not correct, please try again later.');
        }
        if( empty($params['token']) ) {
            $order->onFailure();
			$plugin->getGateway()->getLog()->log('ERROR ExpressCheckoutDetail: '
                    . print_r($e, true), Zend_Log::ERR);
            return false;
            throw new Payment_Model_Exception('There was an error processing your ' .
                    'transaction. Please try again later.');
        }

        // Get details
        try {
            $data = $plugin->getService()->detailExpressCheckout($params['token']);
        } catch( Exception $e ) {
            $order->onFailure();
			$plugin->getGateway()->getLog()->log('ERROR ExpressCheckoutDetail: '
                    . print_r($e, true), Zend_Log::ERR);
           return false;
           throw new Payment_Model_Exception('There was an error processing your ' .
                    'transaction. Please try again later.');
        }

        // Let's log it
        $plugin->getGateway()->getLog()->log('ExpressCheckoutDetail: '
                . print_r($data, true), Zend_Log::INFO);

        // Do payment
        try {
            $rdata = $plugin->getService()->doExpressCheckoutPayment($params['token'],
                    $params['PayerID'], array(
                    'PAYMENTACTION' => 'Sale',
                    'AMT' => $data['AMT'],
                    'CURRENCYCODE' => $data['CURRENCYCODE'],
            ));

        } catch( Exception $e ) {
            try {
                $rdata = $plugin->getService()->doExpressCheckoutPayment($params['token'],
                    $params['PayerID'], array(
                    'PAYMENTACTION' => 'Sale',
                    'AMT' => $data['AMT'],
                    'CURRENCYCODE' => $data['CURRENCYCODE'],
                    ));    
            }
             catch( Exception $e ) {            
            
            $order->onFailure();
            $plugin->getGateway()->getLog()->log('ERROR DoExpressCheckoutPayment: '
                    . print_r($e->getMessage(), true), Zend_Log::ERR);
            return false;           
            throw new Payment_Model_Exception('There was an error processing your ' .
                    'transaction. Please try again later.');
             }
        }

        // Let's log it
        $plugin->getGateway()->getLog()->log('DoExpressCheckoutPayment: '
                . print_r($rdata, true), Zend_Log::INFO);

        // Get payment state
        $paymentStatus = null;
        $orderStatus = null;
        switch( strtolower($rdata['PAYMENTINFO'][0]['PAYMENTSTATUS']) ) {
            case 'created':
            case 'pending':
                $paymentStatus = 'completed';
                $orderStatus = 'complete';
                break;
            case 'completed':
            case 'processed':
            case 'canceled_reversal': // Probably doesn't apply
                $paymentStatus = 'completed';
                $orderStatus = 'complete';
                break;

            case 'denied':
            case 'failed':
            case 'voided': // Probably doesn't apply
            case 'reversed': // Probably doesn't apply
            case 'refunded': // Probably doesn't apply
            case 'expired':  // Probably doesn't apply
            default: // No idea what's going on here
                $paymentStatus = 'failed';
                $orderStatus = 'failed'; // This should probably be 'failed'
                break;
        }

        // Update order with profile info and complete status?
        $order->state = $orderStatus;
        $order->gateway_transaction_id = $rdata['PAYMENTINFO'][0]['TRANSACTIONID'];
        $order->save();
        
        $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onTanglePaymentReturn', array(
          'for' => $order,
        ));
    
        // Insert transaction
        $transactionsTable = Engine_Api::_()->getDbtable('transactions', 'payment');
        $transaction_id = $transactionsTable->insert(array(
                'user_id' => $order->user_id,
                'gateway_id' => 2,
                'timestamp' => new Zend_Db_Expr('NOW()'),
                'order_id' => $order->order_id,
                'type' => 'payment',
                'state' => $paymentStatus,
                'gateway_transaction_id' => $rdata['PAYMENTINFO'][0]['TRANSACTIONID'],
                'amount' => $rdata['AMT'], // @todo use this or gross (-fee)?
                'currency' => $rdata['PAYMENTINFO'][0]['CURRENCYCODE'],
        ));
        
        
       
                    
        $_SESSION["transaction_id"]=$transaction_id;
        if( $paymentStatus == 'okay' || $paymentStatus == "completed") {
            return true;
        }
        else if( $paymentStatus == 'failed' ) {
            $order->onFailure();
        	return false;
            throw new Payment_Model_Exception('Your payment could not be ' .
                    'completed. Please ensure there are sufficient available funds ' .
                    'in your account.');
        }
        else {
			return false;
            throw new Payment_Model_Exception('There was an error processing your ' .
                    'transaction. Please try again later.');
        }
    }
    
    
   
    
}